local skuKeys = KEYS
local deductAmounts = ARGV

-- 参数校验
if #skuKeys ~= #deductAmounts then
    return 1 -- 参数数量不匹配
end

-- 第一阶段：库存检查
for i = 1, #skuKeys do
    local stockStr = redis.call('GET', 'SkuInventoryNum:' .. skuKeys[i]) -- 获取库存字符串
    local stock = tonumber(stockStr) or 0 -- 尝试转换为数字，若失败则设为0
    local deduct = tonumber(deductAmounts[i])

    if not deduct or deduct < 0 then
        return 2 -- 无效的扣减数量
    end

    if stock < deduct then
        return 3 -- 库存不足
    end
end

-- 第二阶段：执行扣减
for i = 1, #skuKeys do
    local deduct = tonumber(deductAmounts[i])
    redis.call('DECRBY','SkuInventoryNum:'.. skuKeys[i], deduct)
end

return 0 -- 成功
